package celiasoft.itasalib.query.resultparser;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import celiasoft.itasalib.query.ResultsMetaInfo;
import celiasoft.itasalib.structures.DataElement;
import celiasoft.itasalib.structures.Show;

public class QueryAllShowResultParser extends IQueryResultParser {

	@SuppressWarnings("unused")
	private static final String TAG = "itasalib.parser.QueryAllShowResultPaser";

	public List<DataElement> parse(Document doc, ResultsMetaInfo meta) {
		
		ArrayList<DataElement> res = new ArrayList<DataElement>();

		NodeList shows =  doc.getElementsByTagName("shows");
		
		if(shows.getLength() < 1 
				|| !shows.item(0).hasChildNodes()){
			return res;
		}
		
		NodeList nodes = shows.item(0).getChildNodes();
		
		if(nodes.getLength() > 0){
			for(int i = 0; i < nodes.getLength(); i++){
				Node n = nodes.item(i);
				
				DataElement el = parseNode(n);
				if(el != null){
					res.add(el);
				}
			}
		}
		
		if(res.size() > 0){
			setMetaData(doc, meta);
		}
		
		return res;
	}

	private DataElement parseNode(Node n) {
		
		Element e = (Element)n;
		
		
		int id = W3CParsingHandler.parseIntValue(e, "id");
		String name = DomHandler.getValue(e, "name");
		int fans = W3CParsingHandler.parseIntValue(e, "fans");
		
		
		Date start = null , end = null;
		
		start = W3CParsingHandler.parseSimpleDateValue(e, "started");
		end = W3CParsingHandler.parseSimpleDateValue(e,"ended");
		
		Show el = new Show(id, name);
		el.setFans(fans);
		el.setStart(start);
		el.setEnd(end);
		
		return el;
	}


	
}
